<template>
    <van-address-edit
        :area-list="areaList"
        show-set-default
        show-delete
        :address-info="AddressInfo"
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="OnSave"
        @delete="OnDelete"
    />
</template>

<script setup>
// 引入省市区数据
import { areaList } from '@vant/area-data';

const { proxy } = getCurrentInstance();

const business = proxy.$business;

// 初始化数据
const AddressInfo = ref({});

const id = ref(proxy.$route.query.id ?? 0);

onBeforeMount(() => GetInfoData());

const GetInfoData = async () =>
{
    const params = {
        busid:business.value.id,
        id:id.value
    }

    const result = await proxy.$http.post({
        url:'/address/info',
        params
    });

    if(result.code === 1)
    {
        const info = result.data;

        AddressInfo.value = {
            name:info.consignee,
            tel:info.mobile,
            areaCode:info.district ? info.district : (info.city ? business.value.city : business.value.province),
            addressDetail:info.address,
            isDefault:info.status == 1 ? true : false
        }
    }else{
        proxy.$fail(result.msg,() => proxy.$router.back());
    }
}

const OnSave = async (values) =>
{
    const params = {
        id:id.value,
        busid:business.value.id,
        consignee:values.name,
        mobile:values.tel,
        code:values.areaCode,
        address:values.addressDetail,
        status:values.isDefault === true ? 1 : 0
    }

    const result = await proxy.$http.post({
        url:'/address/edit',
        params
    });

    if(result.code === 1)
    {
        proxy.$success(result.msg,() => proxy.$router.back());
    }else{
        proxy.$fail(result.msg);
    }
}

const OnDelete = () =>
{
    proxy.$confirm({
        title:'删除',
        message:'是否确认删除该收货地址？'
    }).then(async () =>
    {
        const params = {
            busid:business.value.id,
            id:id.value
        }

        const result = await proxy.$http.post({
            url:'/address/del',
            params
        });

        if(result.code === 1)
        {
            proxy.$success(result.msg,() => proxy.$router.back())
        }else{
            proxy.$fail(result.msg);
        }
    }).catch(() => {});
}

</script>